package com.map.domain;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

public class BaseUrl {
	private String baseurl;
    private int numUrl;
    private List<String> urlList;
    
	public BaseUrl() {
		setNumUrl(0);
		urlList = new ArrayList<String>();
	}
	
	public BaseUrl(String filename) throws IOException {
		try {
			urlList = new ArrayList<String>();
		BufferedReader in = new BufferedReader(new FileReader(filename)); 
		if (in.ready()) {
			String text = in.readLine();
				setNumUrl(1);
			    baseurl = text;
			    baseurl = baseurl + "\n";
			    urlList.add(text);
			    System.out.println("Inside BaseURL Constructor base: " + text);
		}
		while (in.ready()){
		String text = in.readLine();
		if (!text.equals(""))
		{
			System.out.println("Inside BaseURL Constructor base: " + text);
			setNumUrl(getNumUrl() + 1);
		urlList.add(text);
		baseurl = baseurl+text;
		baseurl = baseurl + "\n";
		}
		}
		in.close();
		} catch(IOException ex) {
			baseurl = "";
		}
	}

	public String getBaseurl() {
		return baseurl;
	}

	public void setBaseurl(String baseurl) {
		this.baseurl = baseurl;
	}

	public int getNumUrl() {
		return numUrl;
	}

	public void setNumUrl(int numUrl) {
		this.numUrl = numUrl;
	}
	public void setUrlList(List<String> weblist){
		this.urlList = weblist;
	}
	public List<String> getUrlList() {
		return this.urlList;
	}
	public int getNumfromBaseUrl(String baseurl)
	{
		int count=0;
		while(baseurl.length()>0)
		{
			count++;
			baseurl=baseurl.substring(baseurl.indexOf("\n")+1);
		}
		return count;
	}
	public void setListfromBaseUrl(String baseurl)
	{
		List<String> tmp=new ArrayList<String>();
		String url=null;
		while(baseurl.length()>0)
		{ 
			url=baseurl.substring(0,baseurl.indexOf("\n"));
			try {
				if(!url.startsWith("http"))
					url="http://"+url;
				URL u= new URL (url);
			if(u.getHost().contains("."))
			tmp.add(u.getHost());
			baseurl=baseurl.substring(baseurl.indexOf("\n")+1);
            } catch (MalformedURLException e) {
				System.out.println("Sorry, URL is not correct format: "+ e.getMessage());
				baseurl=baseurl.substring(baseurl.indexOf("\n")+1);
			}
		}
		setUrlList(tmp);
	}
	
	public int getNumfromList()
	{
		return urlList.size();
	}
	
}
